package com.teragadgets.android.comic;

import java.util.Observable;
import java.util.Vector;

import android.content.Context;
import android.os.AsyncTask;

import com.teragadgets.android.comic.datamodel.Comic;
import com.teragadgets.android.comic.datamodel.WebComic;
import com.teragadgets.android.comic.datamodel.WebComicDatabase;
import com.teragadgets.android.comic.feed.ComicFeedParser;

public class ComicListModel extends Observable {

	private WebComic webComic;
	private Vector<Comic> comics;
	private int loaded = 0;
	private int numToLoadEachTime = 10;

	public ComicListModel(Context ctx, String webComicID) {

		WebComicDatabase db = WebComicDatabase.open(ctx);
		webComic = db.fetchComic(webComicID);
		db.close();

		comics = new Vector<Comic>();

		loadComics();
	}

	public void loadComics() {

		new AsyncTask<Object, Object, Vector<Comic>>() {

			@Override
			protected Vector<Comic> doInBackground(Object... arg0) {
				ComicFeedParser parser = new ComicFeedParser(webComic.getFeed(
						loaded, numToLoadEachTime));
				try {
					Vector<Comic> newComics = parser.getComics();
					loaded += numToLoadEachTime;
					return newComics;

				} catch (Exception e) {
					e.printStackTrace();
				}
				return new Vector<Comic>();
			}

			@Override
			protected void onPostExecute(Vector<Comic> result) {
				comics.addAll(result);
				setChanged();
				notifyObservers(false);
			}
		}.execute((Object) null);
	}

	public WebComic getWebComic() {
		return webComic;
	}

	public Vector<Comic> getComics() {
		return comics;
	}

	public WebComic updateWebComic(Context ctx) {
		WebComicDatabase db = WebComicDatabase.open(ctx);
		webComic = db.fetchComic(webComic.getID());
		db.close();
		return webComic;
	}

	public int getLastRead() {
		return webComic.getLastRead();
	}

	public void changeOrder(Context ctx) {
		webComic.changeOrder();
		WebComicDatabase db = WebComicDatabase.open(ctx);
		db.updateOrder(webComic.getID(), webComic.getOrder());
		db.close();

		refresh(ctx);
	}

	public void refresh(Context ctx) {
		comics.removeAllElements();
		loaded = 0;
		loadComics();
	}
}